package cron.core.scheduler;

import cron.core.ResourceTaskScheduler;
import cron.core.scheduler.timer.TimeWheel;
import cron.core.scheduler.trigger.CronTrigger;
import cron.core.scheduler.trigger.FixedRateTrigger;
import cron.core.scheduler.trigger.Trigger;
import cron.core.scheduler.trigger.TriggerType;
import cron.task.plugin.Task;

import java.util.UUID;

/**
 * 触发器调度器
 *
 * @author : willian fu
 * @version : 1.0
 * @date : 2021/3/10 0010 13:24
 */
public class TriggerScheduler implements Scheduler {

    private TimeWheel timeWheel;

    public TriggerScheduler(TimeWheel timeWheel) {
        this.timeWheel = timeWheel;
    }

    /**
     * 启用触发器
     *
     * @param triggerId 触发器实例ID
     */
    @Override
    public void enable(String triggerId) {
        getTriggerInstance(triggerId).enable();
    }

    /**
     * 禁用触发器
     *
     * @param triggerId 触发器实例ID
     */
    @Override
    public void disable(String triggerId) {
        getTriggerInstance(triggerId).disable();
    }

    /**
     * 像时间轮注册一个任务
     *
     * @param task 任务实例
     * @param type 任务触发器类型
     * @param val  任务调度计划
     * @return 任务调度实例ID
     */
    @Override
    public String register(Task task, TriggerType type, Object val) {
        Trigger taskTrigger;
        switch (type) {
            case CRON:
                taskTrigger = new CronTrigger(val.toString(), task);
                break;
            case FIX_RATE:
                taskTrigger = new FixedRateTrigger(Long.parseLong(val.toString()), task);
                break;
            default:
                throw new RuntimeException("没有找到对应的触发器 " + type.toString());
        }
        timeWheel.addTrigger(taskTrigger);
        String triggerId = UUID.randomUUID().toString().replaceAll("-","").substring(8, 24);
        ResourceTaskScheduler.TASK_TRIGGERS.put(triggerId, taskTrigger);
        return triggerId;
    }

    /**
     * 更新调度计划
     *
     * @param triggerId 任务调度实例ID
     */
    @Override
    public void updatePlan(String triggerId, Object rule) {
        getTriggerInstance(triggerId).updateRule(rule);
    }

    /**
     * 通过实例ID获取触发器
     *
     * @param triggerId 触发器实例ID获取
     * @return 触发器实例
     */
    public static Trigger getTriggerInstance(String triggerId) {
        Trigger trigger = ResourceTaskScheduler.TASK_TRIGGERS.get(triggerId);
        /*if (null == trigger) {
            throw new RuntimeException("找不到ID=" + triggerId + "的触发器实例");
        }*/
        return trigger;
    }
}
